package com.jewelry.controller;

import com.jewelry.entity.Cart;
import com.jewelry.entity.CartItem;
import com.jewelry.entity.Product;
import com.jewelry.entity.User;
import com.jewelry.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ProductService productService; // 使用 ProductService 替代 BookService

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    //添加购物车
    @RequestMapping("/putCart")
    public void putCart(Integer productId, HttpSession session) {
        //从session中获取用户信息
        User user = (User) session.getAttribute("user");


        Integer userId = user.getUserId();

        //从redis中获取购物车
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Cart cart = (Cart) opsForValue.get("cart:" + userId);
        //判断购物车是否为空
        if (cart != null) {
            //获取购物车中的商品
            LinkedHashMap<Integer, CartItem> items = cart.getItems();

            Product product = productService.getById(productId);

            //判断购物车中是否已经有该商品
            if (items.containsKey(productId)) {
                //如果有该商品，则更新该商品的数量
                CartItem cartItem = items.get(productId);
                cartItem.setCount(cartItem.getCount() + 1);
                //将修改后的购物车项放回购物车
                items.put(productId, cartItem);
                //BigDecimal 类型的数据的运算
            } else {
                //如果没有该商品，则添加该商品到购物车
                CartItem cartItem = new CartItem(product.getProductId(),product.getProductName(),product.getImageUrl(),product.getPrice(),product.getJprice(),1,false);
                //将购物车项放入购物车
                items.put(productId, cartItem);
            }
            cart.setItems(items);
            cart.sumMoney();

            opsForValue.set("cart:" + userId, cart);
        } else {
            //如果购物车为空，则创建一个新的购物车
            cart = new Cart();

            LinkedHashMap<Integer, CartItem> items = cart.getItems();
            Product product = productService.getById(productId); // 使用 ProductService 获取 Product
            CartItem cartItem = new CartItem(product.getProductId(),product.getProductName(),product.getImageUrl(),product.getPrice(),product.getJprice(),1,false);
            items.put(productId, cartItem);
            cart.sumMoney();

            opsForValue.set("cart:" + userId, cart);
        }
    }
    //删除购物车中的商品
    @RequestMapping("/removeCart")
    public void removeCart(Integer productId, HttpSession session) {
        User user = (User) session.getAttribute("user");

        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Cart cart = (Cart) opsForValue.get("cart:" + user.getUserId());

        LinkedHashMap<Integer, CartItem> items = cart.getItems();

        // Your existing logic for removing products from the cart goes here
        CartItem cartItem = items.get(productId);

        items.remove(productId);

        //总金额是
        cart.setItems(items);
        cart.sumMoney();

        opsForValue.set("cart:" + user.getUserId(), cart);
    }

    // Other methods like showCart, updateCount, getNum remain similar with necessary changes from Book to Product

    // 显示购物车
    @RequestMapping("/showCart")
    public Map showCart(HttpSession session) {
        User user = (User) session.getAttribute("user");
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Cart cart = (Cart) opsForValue.get("cart:" + user.getUserId());
        Map map = new HashMap<>();
        map.put("cart",cart);
        return map;
    }

    @RequestMapping("/showCheckCart")
    public Map showCheckCart(HttpSession session) {
        User user = (User) session.getAttribute("user");
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Cart cart = (Cart) opsForValue.get("cart:" + user.getUserId());
        LinkedHashMap<Integer, CartItem> items = cart.getItems();
        LinkedHashMap<Integer, CartItem> newItems = new LinkedHashMap<>();
        for (Integer productId : items.keySet()) {
            if (items.get(productId).isChecked()) {
                newItems.put(productId, items.get(productId));
            }
        }
        cart.setItems(newItems);
        Map map = new HashMap<>();
        map.put("cart",cart);
        return map;
    }

    // 修改购物车数量
    @RequestMapping("/updateCount")
    public Cart updateCount(Integer productId, Integer count, HttpSession session) {
        User user = (User) session.getAttribute("user");



        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        //获取购物车
        Cart cart = (Cart) opsForValue.get("cart:" + user.getUserId());

        LinkedHashMap<Integer, CartItem> items = cart.getItems();

        //如果count=0，则删除该商品
        if (count <= 0) {
            items.remove(productId);
        }else{
            items.get(productId).setCount(count);
        }

        cart.sumMoney();

        opsForValue.set("cart:" + user.getUserId(), cart);
        return  cart;
    }

    // 获取购物车中产品数量
    @RequestMapping("/getNum")
    public String getNum(HttpSession session) {
        User user = (User) session.getAttribute("user");


        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        Cart cart = (Cart) opsForValue.get("cart:" + user.getUserId());

        int size = cart.getItems().size();
        return String.valueOf(size);
    }
    //将勾选的购物车项更新到购物车
    @PostMapping("/updateCart")
    public Cart updateCart(@RequestBody int[] ids, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Cart cart = (Cart) redisTemplate.opsForValue().get("cart:" + user.getUserId());
        cart.setIds(ids);

        redisTemplate.opsForValue().set("cart:" + user.getUserId(), cart);

        return cart;
    }
    //修改购物车项的选中属性
    @RequestMapping("/updateCartItem")
    public Cart updateCartItem( Integer productId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Cart cart = (Cart) redisTemplate.opsForValue().get("cart:" + user.getUserId());
        LinkedHashMap<Integer, CartItem> items = cart.getItems();
        CartItem cartItem = items.get(productId);
        cartItem.setChecked(!cartItem.isChecked());
        items.put(productId, cartItem);
        cart.sumMoney();
        redisTemplate.opsForValue().set("cart:" + user.getUserId(), cart);
        return cart;
    }
}